package com.lch.mybatis.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;

/**
 * 记录查询sql的时间
 *
 * @author: liuchenhui
 * @create: 2019-05-10 17:39
 **/
@Intercepts({@Signature(type = StatementHandler.class,
        method = "query",
        args = {Statement.class, ResultHandler.class})})
public class SQLQueryTimeIntercepter implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        final long timeMillis = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        String sql = statementHandler.getBoundSql().getSql();

        System.out.println("查询sql:" + sql);
        try {
            return invocation.proceed();
        } finally {
            System.out.println("查询sql:" + sql + ";耗时:" + (System.currentTimeMillis() - timeMillis));
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
